package com.trilink.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.trilink.common.client.HttpParam;
import com.trilink.common.client.HtttpHead;


/**
 * 代理类
 * @author acer
 *
 */
public class MyProxy implements InvocationHandler {
	
	private Class<?> interfaceClass;

	public Object bind(Class<?> cls) {
	    this.interfaceClass = cls;
	    return Proxy.newProxyInstance(cls.getClassLoader(), new Class[] {interfaceClass}, this);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		return processURL(method,args);
	}
	
	/**
	 * 处理请求
	 * @param method
	 * @param args
	 * @return
	 * @throws Exception 
	 */
	private Object processURL( Method method, Object[] args) throws Exception {
		//将参数转换成map集合以便转换成json
		Map<String,Object>paramMap=new HashMap<String,Object>();
		if(args!=null&&args.length>0) {
			Annotation[][] ann=method.getParameterAnnotations();
			if(ann!=null&&ann.length>0) {
				for(int i=0;i<ann.length;i++) {
					for(int j=0;j<ann[i].length;j++) {
						Annotation a=ann[i][j];
						if(a instanceof HttpParam) {
							HttpParam an=(HttpParam)a;
							paramMap.put(an.name(),args[i]);
						}
					}
				}
			}
		}
		//参数转换成json
		Gson gson=new Gson();
		String json=gson.toJson(paramMap);
		//获取url
		HtttpHead head=method.getDeclaredAnnotation(HtttpHead.class);
		if(head==null) {
			return "not request url";
		}
		
		String url=head.url();
		String menthod=head.method();
		int timeout=head.timeout();
		String[] heads=head.header();
		URL ul=new URL(url);
		HttpURLConnection connect=(HttpURLConnection)(ul.openConnection());
		connect.setRequestMethod(menthod);
		connect.setDoOutput(true);
		connect.setDoInput(true);
		connect.setReadTimeout(timeout);
		//设置json格式
		connect.setRequestProperty("accept","application/json");
		if(heads!=null) {
			for(String h:heads) {
				String[]d=h.split(":");
				connect.setRequestProperty(d[0], d[1]);
			}
		}
		if(!paramMap.isEmpty()) {
			byte[] pm=json.getBytes();
			int length=pm.length;
			connect.setRequestProperty("Content-Length", length+"");
			OutputStream out=connect.getOutputStream();
			out.write(pm);
			out.flush();
			out.close();
		}
		if(connect.getResponseCode()==200) {
			InputStream in=connect.getInputStream();
			int len;
			byte[] bb=new byte[1024];
			ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
			while((len=in.read(bb))>0) {
				byteOut.write(bb,0,len);
			}
			in.close();
			byte[] data=byteOut.toByteArray();
			byteOut.close();
			//开始对结果集处理
			Class<?>returnType=method.getReturnType();
			if(returnType.equals(Map.class)) {
				
			}else if(returnType.equals(byte[].class)||returnType.equals(Byte[].class)) {
				return data;
			}else if(returnType.equals(String.class)) {
				return new String(data);
			}else if(returnType.equals(int.class)||returnType.equals(Integer.class)) {
				String rt=new String(data);
				return Integer.parseInt(rt);
			}else {
				//当为一个对象时直接转换成对象
				String rt=new String(data);
				return gson.fromJson(rt, returnType);
			}
			
			
		}else {
			throw new Exception("code:"+connect.getResponseCode());
		}
		
		return null;
	}
}
